package com.woniu.service.impl;

import com.nimbusds.jose.JOSEException;
import com.woniu.entity.HospitalUser;
import com.woniu.mapper.HospitalUserMapper;
import com.woniu.service.UserService;
import com.woniu.utils.JWTUtil;
import com.woniu.utils.ResponseEnum;
import com.woniu.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private RedisTemplate redisTemplateInit;
    @Resource
    private HospitalUserMapper hospitalUserMapper;
    @Override
    public ResponseUtil findAll() {
        List<HospitalUser> hospitalUsers = hospitalUserMapper.selectAll();
        return !hospitalUsers.isEmpty() ? ResponseUtil.get(ResponseEnum.OK,hospitalUsers)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil login(HospitalUser hospitalUser) throws JOSEException {
        if (hospitalUser.getRealName().isEmpty() || hospitalUser.getPassword().isEmpty()) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_ERROR_1);
        }
        HospitalUser loginUser = hospitalUserMapper.findByName(hospitalUser.getRealName());
        if (loginUser==null) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_ERROR_2);
        } else if (!hospitalUser.getPassword().equals(loginUser.getPassword())) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_ERROR_3);
        } else if (loginUser.getStatus() == 0) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_ERROR_4);
        }else {
            loginUser.setPassword(null);
            Map<String, Object> map = new HashMap<>();
            map.put("user",loginUser);
            map.put("id",loginUser.getId());
            String token = JWTUtil.getToken(map);
            redisTemplateInit.opsForValue().set("jwt:loginUser:"+loginUser.getId(),token,2, TimeUnit.DAYS);
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_SUCCESS,token);
        }

    }

    @Override
    public ResponseUtil register(HospitalUser hospitalUser) {
        if (hospitalUser == null) {
            return ResponseUtil.get(ResponseEnum.USER_REGISTER_ERROR_1);
        }
        HospitalUser hospitalUser1 = hospitalUserMapper.selectByAccount(hospitalUser.getAccount());
        if(hospitalUser1!=null){
            return ResponseUtil.get(ResponseEnum.FAIL,"用户已存在");
        }
        hospitalUser.setStatus(1);
        hospitalUser.setCreateTime(new Date());
        hospitalUser.setUpdateTime(new Date());
        Integer i = hospitalUserMapper.insertSelective(hospitalUser);
        return i>0?ResponseUtil.get(ResponseEnum.OK)
                :ResponseUtil.get(ResponseEnum.FAIL);
    }
}
